package ace.cmp.liquibase.autoconfig;

import java.util.Optional;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

/**
 * @author caspar
 * @date 2024/3/1 9:14
 */
public class LiquibaseApplicationContextInitializer
    implements ApplicationContextInitializer<ConfigurableApplicationContext> {

  private void initDuplicateFileModeParam(LiquibaseProperties liquibaseProperties) {
    if (liquibaseProperties == null || !liquibaseProperties.isEnabled()) {
      return;
    }
    Optional.ofNullable(liquibaseProperties)
        .map(LiquibaseProperties::getParameters)
        .map(map -> map.getOrDefault("duplicateFileMode", map.get("duplicate-file-mode")))
        .map(
            value -> {
              String tmpMode;
              if ("ERROR".equalsIgnoreCase(value)) {
                tmpMode = "ERROR";
              } else if ("WARN".equalsIgnoreCase(value)) {
                tmpMode = "WARN";
              } else {
                tmpMode = null;
              }
              return tmpMode;
            })
        .ifPresent(mode -> System.setProperty("liquibase.duplicateFileMode", mode));
  }

  @Override
  public void initialize(ConfigurableApplicationContext applicationContext) {
    LiquibaseProperties properties = this.getFromEnvironment(applicationContext.getEnvironment());
    this.initDuplicateFileModeParam(properties);
  }

  private LiquibaseProperties getFromEnvironment(Environment environment) {

    LiquibaseProperties liquibaseProperties =
        Binder.get(environment)
            .bindOrCreate("spring.liquibase", Bindable.of(LiquibaseProperties.class));

    return liquibaseProperties;
  }
}
